import axios, { AxiosRequestConfig } from 'axios';

function request(url: string, options: AxiosRequestConfig = {}): Promise<any> {
  return new Promise((reslove, reject) => {
    axios({
      url,
      baseURL: process.env.NEXT_PUBLIC_API_PREFIX,
      ...options,
    })
      .then((data) => {
        if (data.data.success) {
          reslove(data.data.data);
        } else {
          reject(data.data);
        }
      })
      .catch((e) => {
        reject(e);
      });
  });
}

const get = <T = any>(
  url: string,
  params: AxiosRequestConfig['params'] = {},
  options: AxiosRequestConfig = {}
): Promise<T> => request(url, { params, ...options });

const post = <T = any>(
  url: string,
  data: AxiosRequestConfig['data'] = {},
  options: AxiosRequestConfig = {}
): Promise<T> =>
  request(url, {
    data,
    method: 'post',
    ...options,
  });

const req = { get, post };

export default req;
